const {query} = require("../../plugins/db");
const uuid = require("node-uuid");
const {md5} = require("../../plugins/md5")
const {PED_SALT,EXPIRE_SIN,PEIVATE_KEY} = require("../../plugins/config");
const jwt = require("jsonwebtoken");
let data;
const s = {
    "type":"SUCCESS",
    "msg":"操作成功"
}
const e = {
    "type":"ERROE",
    "msg":"操作失败"
}
const ep = {
    "type":"ERROR_PARAMS_EXIST",
    "msg":"用户名已存在"
}
//图片上传
function upload(req,res) {
    const file =req.file;
    file.url = `http://localhost:3000/uploads/${file.filename}`;
    res.send(file);
}
//注册
async function registered(req,res){
    let infoGetUser = [req.body.username];
    let sqlGetUser = "select * from user where username=?"
    const result = await query(sqlGetUser,infoGetUser);
    if(result.length !=0){
        data = {
            state:ep,
            data:{}
        }
    }else {
        let time = Date.now()-8*60*60;
        let info = {
            user_id:uuid.v1(),//用户id
            username:req.body.username,
            password:req.body.password,
            user_createtime:time,
            nickname:"该用户还没有设置昵称",
            avatar:"http://localhost:3000/Image/morentouxiang.jpg",
            realstate:1,
            user_state:2,
            companystate:1
        }
        info.password = md5(`${info.password}${PED_SALT}`);
        let sql = "insert into user set ?"
        const results = await query(sql,info);
        data = {
            state: s,
            data:results
        }
    }
    res.send(data);
}
//登录
async function login(req,res){
    let password = md5(`${req.body.password}${PED_SALT}`);
    let info = [req.body.username,password];
    let sql = "select * from user where username=? and password=?";
    const result = await query(sql,info);
    if(result.length == 0){
        data = {
            state:e,
            data:{}
        }
    }else {
        let uid = result[0].user_id;
        let nickname = result[0].nickname;
        //通过jwt生成token
        let token = jwt.sign({uid,nickname}, PEIVATE_KEY, {expiresIn:EXPIRE_SIN});
        data = {
            state: s,
            data: {
                shensu:{
                    activationdate:result[0].activationdate,
                    jubao_id:result[0].jubao_id,
                    username:result[0].username
                },
                token:token,
                userInfo:{
                    uid: result[0].user_id,
                    nickname:result[0].nickname,
                    avatar: result[0].avatar,
                    companystate:result[0].companystate,
                    realstate:result[0].realstate
                }
            }
        }
        if(req.body.type == "" && result[0].activationdate > Date.now()){
            data = {
                state:"s",
                data:result[0].activationdate
            }
        }//返回登录成功
    }
    res.send(data);
}
//获取用户信息
async function getUser(req,res){
    let info = [req.user.uid];
    let sql = "select * from user where user_id=?";
    const result = await query(sql,info);
    result[0].password = ''
    data = {
        state:s,
        data:result[0]
    }
    res.send(data);
}
async function getUserNumbering(req,res){
    let info = [req.user.uid];
    const help = await query("select count(*) as count from help where user_id=?",info);
    const article = await query("select count(*) as count from article where user_id=?",info);
    const activity = await query("select count(*) as count from activity where user_id=?",info);
    const oldstuff = await query("select count(*) as count from oldstuff where user_id=?",info);
    const job = await query("select count(*) as count from job where user_id=?",info);
    data = {
        state:s,
        data:{
            help:help[0].count,
            activity:activity[0].count,
            job:job[0].count,
            oldstuff:oldstuff[0].count,
            article:article[0].count
        }
    }
    res.send(data);
}
//更新用户信息
async function updateUser(req,res){
    if(req.body.m=="student"){
        let info = [req.body.realname,req.body.studentid,req.body.studentcard,2,req.user.uid];
        let sql = "update user set realname=?,studentid=?,studentcard=?,realstate=? where user_id=?";
        const result = await query(sql,info);
        data = {
            state:s,
            data:result
        }
    }
    if(req.body.m=="company"){
        let info = [req.body.companyname,req.body.companyimg,2,req.user.uid];
        let sql = "update user set companyname=?,companyimg=?,companystate=? where user_id=?";
        const result = await query(sql,info);
        data = {
            state:s,
            data:result
        }
    }
    if(req.body.m=="user"){
        let info = [
            req.body.avatar,
            req.body.nickname,
            req.body.synopsis,
            req.body.mail,
            req.body.qq,
            req.body.phone,
            req.user.uid
        ];
        let sql = "update user set avatar=?,nickname=?,synopsis=?,mail=?,qq=?,phone=? where user_id=?";
        const result = await query(sql,info);
        console.log(result);
        if(result.affectedRows === 1){
            let info = [req.user.uid];
            let sql = "select * from user where user_id=?";
            const result = await query(sql,info);
            data = {
                state:s,
                data: {
                    userInfo: result[0]
                }
            }
        }else {
            data = {
                state:e,
                data:{}
            }
        }
    }
    res.send(data);
}
//创建求助
async function createHelp(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        help_id: uuid.v1(),   //互助id
        user_id: req.user.uid,//  用户di
        help_title: req.body.help_title,// 标题
        help_lable: req.body.help_lable,// 分类
        help_tag: req.body.help_tag,// 分类
        help_content: req.body.help_content,//内容
        help_img: req.body.help_img,//图片
        createtime: time,//创建时间
        updatetime: time,//更新时间
        help_favour_num: 0,//点赞数
        help_read_num: 0,//浏览量
        help_state: 0, //状态
        help_istop: 0,//是否置顶
        ispublic: 0,//是否显示
        nickname:req.user.nickname
    }
    let sql = "insert into help set ?";
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//用户获取自己的求助列表
async function getHelpList(req,res){
    let sql1 = "select count(*) as count from help where user_id=?";
    let info1 = [req.user.uid];
    const counts = await query(sql1, info1);
    let count = counts[0].count;
    let page = (req.body.page - 1) * req.body.pagesize;
    let pagesize = req.body.pagesize *= 1;
    let info = [req.user.uid, pagesize, page];
    let sql = "select * from help where user_id=? limit ? offset ?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }   //    数据库里面没找到配对的内容返回参数
    } else {
        data = {
            state: s,
            data: result,
            count: count
        }
    }
    // console.log(data)
    // console.log(result)
    res.send(data);
}
//求助详情
async function getHelpDetails(req,res){
    let info = [req.body.id];
    let sql = "select * from help where help_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//修改求助
async function updateHelp(req,res){
    let info = [
        req.body.help_title,
        req.body.help_lable,
        req.body.help_content,
        req.body.help_img,
        req.user.uid,
        req.body.id
    ];
    let sql = "update help set help_title =?,help_lable=?,help_content=?,help_img=? where user_id =? and help_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//删除求助10
async function deleteHelp(req,res){
    let info = [req.body.help_id, req.user.uid];
    let sql = "delete from help where help_id=? and user_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: {
            }
        }
    }
    //console.log(result);
    res.send(data);
}
//创建活动
async function createActivity(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        activity_id: uuid.v1(),   //活动id
        user_id: req.user.uid,//  用户di
        activity_title: req.body.activity_title,// 标题
        activity_lable: req.body.activity_lable,// 标签
        activity_type: req.body.activity_type,// 类型
        activity_content: req.body.activity_content,//内容
        activity_locale: req.body.activity_locale,//地点
        activity_impose: req.body.activity_impose,//是否限制人数
        createtime: time,//创建时间
        activity_num: req.body.activity_num,//人数
        activity_statetime: req.body.activity_statetime,//活动开始时间
        activity_endtime: req.body.activity_endtime,//活动结束时间
        updatetime: time,//更新时间
        activity_favour_num: 0,//点赞数
        activity_read_num: 0,//浏览量
        activity_state: 0, //状态
        activity_istop: 0,//是否置顶
        ispublic: 0,//是否显示
    }
    let sql = "insert into activity set ?";
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//用户获取自己的活动列表
async function getActivityList(req,res){
    let sql1 = "select count(*) as count from activity where user_id=?";
    let info1 = [req.user.uid];
    const counts = await query(sql1, info1);
    let count = counts[0].count;
    let page = (req.body.page - 1) * req.body.pagesize;
    let pagesize = req.body.pagesize *= 1;
    let info = [req.user.uid, pagesize, page];
    let sql = "select * from activity where user_id=? limit ? offset ?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }   //    数据库里面没找到配对的内容返回参数
    } else {
        data = {
            state: s,
            data: result,
            count: count
        }
    }
    // console.log(data)
    // console.log(result)
    res.send(data);
}
//活动详情
async function getActivityDetails(req,res){
    let info = [req.body.id];
    let sql = "select * from activity where activity_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//修改活动
async function updateActivity(req,res){
    let updatetime = Date.now()-8*60*60;
    let info = [
        req.body.activity_title,
        req.body.activity_lable,
        req.body.activity_content,
        req.body.activity_locale,
        req.body.activity_type,
        req.body.activity_impose,
        req.body.activity_num,
        req.body.activity_statetime,
        req.body.activity_endtime,
        updatetime,
        req.user.uid,
        req.body.id];
    let sql = "update activity set activity_title =?,activity_lable=?,activity_content=?,activity_locale=?,activity_type=?,"+
        "activity_impose=?,activity_num=?,activity_statetime=?,activity_endtime=?,updatetime=? where user_id =? and activity_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//删除活动
async function deleteActivity(req,res){
    let info = [req.body.activity_id, req.user.uid];
    let sql = "delete from activity where activity_id=? and user_id=?";
    let sql1 = "delete from joins where conten_id=?";
    const result = await query(sql, info);
    const result1 = await query(sql1, [req.body.activity_id])
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: {
            }
        }
    }
    //console.log(result);
    res.send(data);
}
//获取被jion列表
async function getJoinsList(req,res){
    let info = [req.body.id];
    let sql = "select * from joins,user where user.user_id=joins.user_id and joins.content_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }   //    数据库里面没找到配对的内容返回参数
    } else {
        data = {
            state: s,
            data: result,
        }
    }
    //console.log(data);
    //console.log(result);
    res.send(data);
}
//获取jion列表
async function joinsList(req,res){
    let info = [req.user.uid];
    let sql = "select * from joins";
    if(req.body.type === "oldstuffcontent"){sql = `${sql},oldstuff where oldstuff.oldstuff_id`}
    if(req.body.type === "activitycontent"){sql = `${sql},activity where activity.activity_id`}
    sql = `${sql}=joins.content_id and joins.user_id=?`;
    const result = await query(sql, info);
    data = {
        state:s,
        data:result
    }
    //console.log(result);
    res.send(data);
}
//删除join
async function deleteJoin(req,res){
    let info = [req.body.id, req.user.uid];
    let sql = "delete from joins where join_id=? and user_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: {
            }
        }
    }
    //console.log(result);
    res.send(data);
}
//添加二手信息
async function createOldStuff(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        oldstuff_id: uuid.v1(),   //二手id
        user_id: req.user.uid,//  用户di
        oldstuff_img: req.body.oldstuff_img,// 标题
        oldstuff_name: req.body.oldstuff_name,// 标签
        oldstuff_lable: req.body.oldstuff_lable,// 类型
        oldstuff_price: req.body.oldstuff_price,//内容

        oldstuff_content: req.body.oldstuff_content,//内容
        createtime: time,//创建时间
        updatetime: time,//更新时间
        oldstuff_favour_num: 0,//点赞数
        oldstuff_read_num: 0,//浏览量
        oldstuff_state: 0, //状态
        oldstuff_istop: 0,//是否置顶
        ispublic: 0,//是否显示
    };
    let sql = 'insert into oldstuff set ?';
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//获取二手列表
async function getOldStuffList(req,res){
    let sql1 = "select count(*) as count from oldstuff where user_id=?";
    let info1 = [req.user.uid];
    const counts = await query(sql1, info1);
    let count = counts[0].count;
    let page = (req.body.page - 1) * req.body.pagesize;
    let pagesize = req.body.pagesize *= 1;
    let info = [req.user.uid, pagesize, page];
    let sql = "select * from oldstuff where user_id=? limit ? offset ?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }   //    数据库里面没找到配对的内容返回参数
    } else {
        data = {
            state: s,
            data: result,
            count: count
        }
    }
    // console.log(data)
    // console.log(result)
    res.send(data);
}
//获取二手详情
async function getOldStuffDetails(req,res){
    let info = [req.body.id];
    let sql = "select * from oldstuff where oldstuff_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//修改二手信息
async function updateOldStuff(req,res){
    let info = [
        req.body.oldstuff_img,
        req.body.oldstuff_name,
        req.body.oldstuff_price,
        req.body.oldstuff_content,
        req.body.oldstuff_lable,
        req.user.uid,
        req.body.oldstuff_id];
    let sql = "update oldstuff set oldstuff_img=?,oldstuff_name=?,oldstuff_price=?,"+
        "oldstuff_content=?,oldstuff_lable=? where user_id =? and oldstuff_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//删除二手信息
async function deleteOldStuff(req,res){
    let info = [req.body.oldstuff_id, req.user.uid];
    let sql = "delete from oldstuff where oldstuff_id=? and user_id=?";
    let sql1 = "delete from joins where content_id=?";
    const result = await query(sql, info);
    const result1 = await query(sql1, [req.body.oldstuff_id]);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: {
            }
        }
    }
    //console.log(result);
    res.send(data);
}
//获取个人公司详情
async function getCompany(req,res){
    let info = [req.user.uid];
    let sql = "select * from company where user_id=?";
    const result = await query(sql, info);
    let company;
    if(result.length!==0) {
        company = result[0]
    };
    let sql1 = "select * from job where user_id=?";
    const resultJob = await query(sql1, info);
    data = {
        state:s,
        data:{
            company:company,
            joblist:resultJob
        }
    }
    // console.log(data)
    // console.log(result)
    res.send(data);
}
//修改公司信息
async function changeCompany(req,res){
    let info = [req.body.company_mail,req.body.company_name,req.body.company_scale,req.body.company_content,req.body.company_id,req.user.uid];
    let sql = "update company set company_name=?,company_scale=?,company_content=? where company_id =? and user_id=?";
    const result = await query(sql, info);
    data = {
        state: s,
        data: result[0]
    }

    //console.log(result);
    res.send(data);
}
//添加岗位
async function createJob(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        job_id: uuid.v1(),   //id
        user_id: req.user.uid,//  用户di
        company_id: req.body.company_id,
        job_name: req.body.job_name,// 岗位铭恒
        job_salary: req.body.job_salary,// 薪资
        job_num: req.body.job_num,//人数
        job_lable: req.body.job_lable,//类型
        job_content: req.body.job_content,//内容
        job_createtime: time,//创建时间
        job_updatetime: time,//更新时间
        job_favour_num: 0,//点赞数
        job_read_num: 0,//浏览量
        job_state: 0, //状态
        job_istop: 0,//是否置顶
        ispublic: 0,//是否显示
    }
    let sql = 'insert into job set ?';
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//删除工作
async function deleteJob(req,res){
    let info = [req.body.job_id, req.user.uid];
    let sql = "delete from job where job_id=? and user_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: {
            }
        }
    }
    //console.log(result);
    res.send(data);
}
//添加文章
async function createArticle(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        article_id: uuid.v1(),   //id
        user_id: req.user.uid,//  用户di
        article_title: req.body.article_title,// 标题
        article_introduction: req.body.article_introduction,// 简介
        article_lable: req.body.article_lable,//类型
        article_content: req.body.article_content,//内容

        article_createtime: time,//创建时间
        article_updatetime: time,//更新时间
        article_favour_num: 0,//点赞数
        article_read_num: 0,//浏览量
        article_state: 0, //状态
        article_istop: 0,//是否置顶
        ispublic: 0,//是否显示
    };
    let sql = 'insert into article set ?';
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//文章列表
async function getArticleList(req,res){
    let sql1 = "select count(*) as count from article where user_id=?";
    let info1 = [req.user.uid];
    const counts = await query(sql1, info1);
    let count = counts[0].count;
    let page = (req.body.page - 1) * req.body.pagesize;
    let pagesize = req.body.pagesize *= 1;
    let info = [req.user.uid, pagesize, page];
    let sql = "select * from article where user_id=? limit ? offset ?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }   //    数据库里面没找到配对的内容返回参数
    } else {
        data = {
            state: s,
            data: result,
            count: count
        }
    }
    // console.log(data)
    // console.log(result)
    res.send(data);
}
//文章详情
async function getArticleDetails(req,res){
    let info = [req.body.id];
    let sql = "select * from article where article_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//修改文章
async function updateArticle(req,res){
    let info = [
        req.body.article_title,
        req.body.article_lable,
        req.body.article_content,
        req.body.article_introduction,
        req.user.uid,
        req.body.article_id
    ];
    let sql = "update article set article_title=?,article_lable=?,article_content=?,"+
        "article_introduction=? where user_id =? and article_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}
//删除文章
async function deleteArticle(req,res){
    let info = [req.body.article_id, req.user.uid];
    let sql = "delete from article where article_id=? and user_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: {
            }
        }
    }
    //console.log(result);
    res.send(data);
}
//添加反馈
async function createFeedback(req,res){
    let time = Date.now()-8*60*60;
    let info = {
        fankui_id: uuid.v1(),   //id
        fankui_content: req.body.fankui_content,//内容
        fankui_user: req.body.fankui_user,//  用户di
        fankui_createtime: time,//创建时间
        fankui_state: 0, //状态
    };
    let sql = 'insert into fankui set ?';
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//添加申诉
async function createAppeal(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        shensu_id: uuid.v1(),   //id
        shensu_content: req.body.shensu_content,//内容
        shensu_user: req.body.shensu_user,//  用户
        shensu_jubao_id: req.body.shensu_jubao_id,
        shensu_createtime: time,//创建时间
        shensu_state: 0, //状态
    }
    let sql = 'insert into shensu set ?';
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//添加举报
async function createReport(req,res){
    let time = Date.now() - 8 * 60 * 60;
    let info = {
        jubao_id: uuid.v1(),   //id
        jubao_content: req.body.jubao_content,//内容
        jubao_user: req.body.jubao_user,//  用户di
        jubao_img: req.body.jubao_img,
        jubao_url: req.body.jubao_url,
        jubao_createtime: time,//创建时间
        jubao_state: 0, //状态
    };
    let sql = 'insert into jubao set ?';
    const result = await query(sql, info);
    data = {
        state: s,
        data: {}
    }
    res.send(data);
}
//举报详情
async function getReportContent(req,res){
    let info = [req.body.id];
    let sql = "select * from jubao where jubao_id=?";
    const result = await query(sql, info);
    if (result.length == 0) {
        data = {
            state: e,
            data: {
            }
        }
    } else {
        data = {
            state: s,
            data: result[0]
        }
    }
    //console.log(result);
    res.send(data);
}

module.exports = {
    upload,
    registered,
    login,
    getUser,
    getUserNumbering,
    updateUser,
    createHelp,
    getHelpList,
    getHelpDetails,
    updateHelp,
    deleteHelp,
    createActivity,
    getActivityList,
    getActivityDetails,
    updateActivity,
    deleteActivity,
    getJoinsList,
    joinsList,
    deleteJoin,
    createOldStuff,
    getOldStuffList,
    getOldStuffDetails,
    updateOldStuff,
    deleteOldStuff,
    getCompany,
    changeCompany,
    createJob,
    deleteJob,
    createArticle,
    getArticleList,
    getArticleDetails,
    updateArticle,
    deleteArticle,
    createFeedback,
    createAppeal,
    createReport,
    getReportContent
}
